package com.lyf.boot.modules.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyf.boot.base.system.entity.SysDict;
import com.lyf.boot.constant.CacheConstant;
import com.lyf.boot.core.model.DictCache;
import com.lyf.boot.core.model.OptionVo;
import com.lyf.boot.core.model.PageInfo;
import com.lyf.boot.core.service.IDictService;
import com.lyf.boot.exception.ServiceException;
import com.lyf.boot.modules.system.dao.SysDictDao;
import com.lyf.boot.modules.system.entity.dto.SysDictDto;
import com.lyf.boot.modules.system.entity.dto.SysDictPageDto;
import com.lyf.boot.modules.system.entity.dto.SysDictTypeDto;
import com.lyf.boot.modules.system.entity.dto.SysDictTypePageDto;
import com.lyf.boot.modules.system.entity.vo.SysDictTypeVo;
import com.lyf.boot.modules.system.entity.vo.SysDictVo;
import com.lyf.boot.modules.system.service.ISysDictService;
import com.lyf.boot.utils.MapstructUtil;
import com.lyf.boot.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Luyufan
 * @date 2023/7/7 16:53
 */
@Service
@RequiredArgsConstructor
public class SysDictServiceImpl implements ISysDictService, IDictService {

    private final SysDictDao sysDictDao;

    @Override
    public PageInfo<SysDictTypeVo> getSysDictTypePage(SysDictTypePageDto dto) {
        Page<SysDictTypeVo> page = dto.of();
        return PageInfo.build(sysDictDao.selectSysDictTypePage(page, dto));
    }

    @Override
    public List<OptionVo> getSysDictTypeList(){
        return sysDictDao.selectSysDictTypeList();
    }

    @Override
    public List<SysDictVo> getSysDictListByType(String dictType) {
        return sysDictDao.selectSysDictByDictType(dictType);
    }

    @Override
    public Map<String, String> getSysDictMapByType(String dictType) {
        Map<String, String> resultMap = new HashMap<>(0);
        List<SysDictVo> list = getSysDictListByType(dictType);
        if (CollUtil.isNotEmpty(list)){
            resultMap = list.parallelStream().collect(Collectors.toMap(SysDictVo::getDictKey, SysDictVo::getDictValue));
        }
        return resultMap;
    }

    @Override
    public DictCache getSysDict(String dictType, String dictKey) {
        String dictRedisKey = CacheConstant.DICT_CACHE + dictType;
        Object cacheObj = RedisUtil.getCacheMapValue(dictRedisKey, dictKey);
        if(cacheObj == null){
            return null;
        }
        return (DictCache) cacheObj;
    }

    @Override
    public String getSysDictValue(String dictType, String dictKey) {
        DictCache dictCache = getSysDict(dictType, dictKey);
        return null == dictCache ? null : dictCache.getDictValue();
    }

    @Override
    public void asyncSysDict() {
        List<SysDict> sysDictList = sysDictDao.selectList(null);
        if(CollUtil.isEmpty(sysDictList)){
            return;
        }
        List<SysDict> typeList = sysDictList.stream().filter(o -> ObjectUtil.isNull(o.getDictType())).toList();
        List<SysDict> dictList = sysDictList.stream().filter(o -> ObjectUtil.isNotNull(o.getDictType())).collect(Collectors.toList());
        List<DictCache> cacheList = BeanUtil.copyToList(dictList, DictCache.class);
        Map<String, List<DictCache>> dictGroup = cacheList.parallelStream().collect(Collectors.groupingBy(DictCache::getDictType));

        typeList.parallelStream().forEach(type -> {
            String redisKey = CacheConstant.DICT_CACHE + type.getDictKey();
            List<DictCache> subList = dictGroup.get(type.getDictKey());
            if(CollUtil.isNotEmpty(subList)){
                Map<String, Object> dictMap = subList.parallelStream().collect(Collectors.toMap(DictCache::getDictKey, Function.identity()));
                RedisUtil.setCacheMap(redisKey, dictMap);
            }
        });
    }

    @Override
    public SysDictTypeVo getSysDictTypeInfo(Long dictId) {
        SysDict sysDict = sysDictDao.selectById(dictId);
        if(sysDict != null){
            return MapstructUtil.convert(sysDict, SysDictTypeVo.class);
        }
        return null;
    }

    @Override
    public void saveSysDictType(SysDictTypeDto dto) {
        boolean exists = sysDictDao.exists(Wrappers.<SysDict>lambdaQuery()
                .eq(SysDict::getDictKey, dto.getDictKey()));
        if(exists){
            throw new ServiceException("字典类型已存在");
        }
        SysDict sysDict = MapstructUtil.convert(dto, SysDict.class);
        sysDictDao.insert(sysDict);
    }

    @Override
    public void updateSysDictType(SysDictTypeDto dto) {
        boolean exists = sysDictDao.exists(Wrappers.<SysDict>lambdaQuery()
                .eq(SysDict::getDictKey, dto.getDictKey()).ne(SysDict::getDictId, dto.getDictId()));
        if(exists){
            throw new ServiceException("字典类型已存在");
        }
        SysDict sysDict = MapstructUtil.convert(dto, SysDict.class);
        sysDictDao.updateById(sysDict);
    }

    @Override
    public void deleteSysDictType(List<Long> ids) {
        sysDictDao.deleteByIds(ids);
    }

    @Override
    public PageInfo<SysDictVo> getSysDictPage(SysDictPageDto dto) {
        Page<SysDictVo> page = dto.of();
        return PageInfo.build(sysDictDao.selectSysDictPage(page, dto));
    }

    @Override
    public SysDictVo getSysDictInfo(Long dictId) {
        SysDict sysDict = sysDictDao.selectById(dictId);
        if(sysDict != null){
            return MapstructUtil.convert(sysDict, SysDictVo.class);
        }
        return null;
    }

    @Override
    public void saveSysDict(SysDictDto dto) {
        boolean exists = sysDictDao.exists(Wrappers.<SysDict>lambdaQuery()
                .eq(SysDict::getDictType, dto.getDictType())
                .eq(SysDict::getDictKey, dto.getDictKey()));
        if(exists){
            throw new ServiceException("字典键已存在");
        }
        SysDict sysDict = MapstructUtil.convert(dto, SysDict.class);
        sysDictDao.insert(sysDict);
    }

    @Override
    public void updateSysDict(SysDictDto dto) {
        SysDict sysDictDb = sysDictDao.selectById(dto.getDictId());
        if (sysDictDb == null) {
            throw new ServiceException("字典不存在");
        }
        boolean exists = sysDictDao.exists(Wrappers.<SysDict>lambdaQuery()
                .eq(SysDict::getDictType, sysDictDb.getDictType())
                .eq(SysDict::getDictKey, dto.getDictKey())
                .ne(SysDict::getDictId, dto.getDictId()));
        if(exists){
            throw new ServiceException("字典键已存在");
        }
        SysDict sysDict = MapstructUtil.convert(dto, SysDict.class);
        sysDictDao.updateById(sysDict);
    }

    @Override
    public void deleteSysDict(List<Long> ids) {
        sysDictDao.deleteByIds(ids);
    }

    /**
     * 根据字典类型和字典值获取字典标签
     *
     * @param dictType  字典类型
     * @param dictKey 字典值
     * @param separator 分隔符
     * @return 字典标签
     */
    @Override
    public String getDictValue(String dictType, String dictKey, String separator) {
        StringBuilder propertyString = new StringBuilder();
        List<SysDictVo> dataList = getSysDictListByType(dictType);

        if (StrUtil.containsAny(dictKey, separator) && CollUtil.isNotEmpty(dataList)) {
            for (SysDictVo dict : dataList) {
                for (String value : dictKey.split(separator)) {
                    if (value.equals(dict.getDictKey())) {
                        propertyString.append(dict.getDictValue()).append(separator);
                        break;
                    }
                }
            }
        } else {
            for (SysDictVo dict : dataList) {
                if (dictKey.equals(dict.getDictKey())) {
                    return dict.getDictValue();
                }
            }
        }
        return StrUtil.removeSuffix(propertyString.toString(), separator);
    }

    /**
     * 根据字典类型和字典标签获取字典值
     *
     * @param dictType  字典类型
     * @param dictKey 字典标签
     * @param separator 分隔符
     * @return 字典值
     */
    @Override
    public String getDictKey(String dictType, String dictKey, String separator) {
        StringBuilder propertyString = new StringBuilder();
        List<SysDictVo> dataList = getSysDictListByType(dictType);

        if (StrUtil.containsAny(dictKey, separator) && CollUtil.isNotEmpty(dataList)) {
            for (SysDictVo dict : dataList) {
                for (String label : dictKey.split(separator)) {
                    if (label.equals(dict.getDictValue())) {
                        propertyString.append(dict.getDictKey()).append(separator);
                        break;
                    }
                }
            }
        } else {
            for (SysDictVo dict : dataList) {
                if (dictKey.equals(dict.getDictValue())) {
                    return dict.getDictKey();
                }
            }
        }
        return StrUtil.removeSuffix(propertyString.toString(), separator);
    }
}
